package com.weidey.blogWeb.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.weidey.blog.domain.Comment;
import com.weidey.blogWeb.domain.WebComment;
import com.weidey.blogWeb.mapper.WebCommentMapper;
import com.weidey.blogWeb.mapper.WebUserMapper;
import com.weidey.blogWeb.service.ILikeService;
import com.weidey.blogWeb.service.IWebCommentService;
import com.weidey.common.core.domain.AjaxResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WebCommentServiceImpl implements IWebCommentService {


    @Resource
    private WebCommentMapper webCommentMapper;

    @Resource
    private ILikeService likeService;

    @Override
    public void save(Comment comment) {
        webCommentMapper.save(comment);
    }

    @Override
    public AjaxResult commentGet(Integer id, Boolean order) {
        //根据文章id 获取 这篇文章的 全部评论
        List<WebComment> commentSqlDate  = webCommentMapper.selectCommentWithUser(id);

        // 为每条评论设置 点赞量
        commentSqlDate.forEach(comment -> comment.setLikes(likeService.getCount(4,comment.getId())));

        //按时间排序
        if (order)
        {
            commentSqlDate.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));
        }
        // 过滤出根评论（pid 不为 null 的评论）
        List<WebComment> rootComments = commentSqlDate.stream()
                .filter(comment -> comment.getPid() == null)
                .collect(Collectors.toList());
        // 构建子评论映射
        Map<Integer, List<WebComment>> pidToComments = new HashMap<>();
        for (WebComment comment : commentSqlDate) {
            if (comment.getPid() != null) {
                pidToComments.computeIfAbsent(comment.getPid().intValue(), k -> new ArrayList<>()).add(comment);
            }
        }
        // 分配子评论到根评论
        for (WebComment rootComment : rootComments) {
            List<WebComment> children = pidToComments.getOrDefault(rootComment.getId().intValue(), Collections.emptyList());
            rootComment.setChildrenComment(children);
        }
        //打包Jonson 发给前端
        JSONObject commentListJson =  new JSONObject();
        commentListJson.put("comments",rootComments);
        commentListJson.put("count",commentSqlDate.size());
        return AjaxResult.success(commentListJson);
    }
}
